﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Controllers.TemporaryDocument;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface.SmallBatchTrial;
using RndMaterialDisposalService.Services.Interface.TemporaryDocument;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System.Collections.Generic;

namespace RndMaterialDisposalService.Controllers.SmallBatchTrial
{
    /// <summary>
    /// 小批量试用跟踪电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SmallBatchTrialController : ControllerBase
    {
        private ILogger<SmallBatchTrialController> logger;
        private readonly string ProcessFullName = "SmallBatchTrial\\SmallBatchTrial";
        private ISmallBatchTrialService ismallBatchTrialService;
        private IConfiguration configuration;
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        public SmallBatchTrialController(ILogger<SmallBatchTrialController> _logger,
            ISmallBatchTrialService _ismallBatchTrialService,
            IConfiguration _configuration) 
        {
            logger = _logger;
            ismallBatchTrialService = _ismallBatchTrialService;
            configuration = _configuration;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <param name="applicationNumber"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? applicationNumber)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new SmallBatchTrialElectronFlowReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 返回小批量试用跟踪电子流报表主数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SmallBatchTrialReportFormData")]
        [PageList]
        public IActionResult SmallBatchTrialReportFormData(SmallBatchTrialReportConditionModel input)
        {
            var list = ismallBatchTrialService.GetSmallBatchTrialReportFormPageList(input);
            int count = ismallBatchTrialService.GetSmallBatchTrialReportFormData(input).Count();

            var result = ApiResponsePageList<SmallBatchTrialReportFormModel>.CreatePageListByResult(list, input.pageIndex, input.pageSize, count);

            return Ok(result);
        }

        /// <summary>
        /// 新增报表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SavaSmallBatchTrialReportFormData")]
        public async Task<IActionResult> SavaSmallBatchTrialReportFormData(SmallBatchTrialReportDataModel input)
        {
            int count = 0;
            string _ProcInstId = input.ProcInstId ?? "0";
            try
            {
                if (input != null)
                {
                    SmallBatchTrialBusinessDataModel item = new SmallBatchTrialBusinessDataModel();
                    item.SysId = Guid.NewGuid();
                    item.ProcessFolio = input.ProcessFolio.Trim() ?? "";
                    item.ProcInstId = input.ProcInstId ?? "";
                    item.TrialSource = input.TrialSource ?? "";
                    item.ElectronicFlowLink = input.ElectronicFlowLink ?? "";
                    item.RawMaterialCode = input.RawMaterialCode ?? "";
                    item.RawProductType = input.RawProductType ?? "";
                    item.RawManufacturer = input.RawManufacturer ?? "";
                    item.NewMaterialCode = input.NewMaterialCode ?? "";
                    item.NewProductType = input.NewProductType ?? "";
                    item.NewManufacturer = input.NewManufacturer ?? "";
                    item.Oem = input.Oem;
                    item.MaterialPreparationParty = input.MaterialPreparationParty ?? "";
                    item.TrialBackground = input.TrialBackground ?? "";
                    item.TrialObjective = input.TrialObjective ?? "";
                    item.KeyConcerns = input.KeyConcerns ?? "";
                    item.TrackingEngineer = input.TrackingEngineer ?? "";
                    item.ComponentEngineer = input.ComponentEngineer ?? "";
                    item.OutsourcingSQE = input.OutsourcingSQE ?? "";
                    item.OutsourcingEngineer = input.OutsourcingEngineer ?? "";
                    item.CCPersonnel = input.CCPersonnel ?? "";
                    item.SQEEngineer = input.SQEEngineer ?? "";
                    item.Task1ThisProcessingCount = input.Task1ThisProcessingCount ?? "";
                    item.Task1IsEngineerApproval = input.Task1IsEngineerApproval;
                    item.Task1AnomalyAnalysisProcess = input.Task1AnomalyAnalysisProcess ?? "";
                    item.Task1IsAbnormalMaterialRelated = input.Task1IsAbnormalMaterialRelated;
                    item.Task1IsTransitionToTrialProduction = input.Task1IsTransitionToTrialProduction;
                    item.Task1ApproveName = input.Task1ApproveName ?? "";
                    item.Task3TrialProductionConclusion = input.Task3TrialProductionConclusion;
                    item.Task3FinishProductHandlingMethod = input.Task3FinishProductHandlingMethod;
                    item.Task3RawMaterialHandlingMethod = input.Task3RawMaterialHandlingMethod ?? "";
                    item.Task3SubsequentOperations = input.Task3SubsequentOperations ?? "";
                    item.Task4TrialProductionConclusion = input.Task4TrialProductionConclusion;
                    item.Task4FinishProductHandlingMethod = input.Task4FinishProductHandlingMethod;
                    item.Task4RawMaterialHandlingMethod = input.Task4RawMaterialHandlingMethod ?? "";
                    item.Task4SemimanufacturesHandlingMethod = input.Task4SemimanufacturesHandlingMethod ?? "";
                    item.Task4RestrictedScopeOtherMethods = input.Task4RestrictedScopeOtherMethods ?? "";
                    item.Task4SubsequentOperations = input.Task4SubsequentOperations ?? "";
                    item.Task4IsDirectorApproval = input.Task4IsDirectorApproval;
                    item.Task4ApproveName = input.Task4ApproveName ?? "";
                    item.Task5TrialProductionConclusion = input.Task5TrialProductionConclusion;
                    item.Task5FinishProductHandlingMethod = input.Task5FinishProductHandlingMethod;
                    item.Task5RawMaterialHandlingMethod = input.Task5RawMaterialHandlingMethod ?? "";
                    item.Task5SemimanufacturesHandlingMethod = input.Task5SemimanufacturesHandlingMethod ?? "";
                    item.Task5RestrictedScopeOtherMethods = input.Task5RestrictedScopeOtherMethods ?? "";
                    item.Task5SubsequentOperations = input.Task5SubsequentOperations ?? "";
                    item.CreatedBy = input.CreatedBy ?? "";
                    item.CreateDate = Convert.ToDateTime(input.CreateDate);
                    item.LastUpdatedBy = input.LastUpdatedBy ?? "";
                    item.LastUpdateDate = Convert.ToDateTime(input.LastUpdateDate);

                    List<SmallBatchTrialBusinessSubtableDataModel> list = new List<SmallBatchTrialBusinessSubtableDataModel>();
                    input.materialTrackingDetailsList.ForEach((x) => {
                        list.Add(new SmallBatchTrialBusinessSubtableDataModel
                        {
                            SysId = Guid.NewGuid(),
                            ProcInstId = input.ProcInstId ?? "",
                            ReactKey = x.key,
                            ProductLine = x.productLine ?? "",
                            EngineerName = x.engineerName ?? "",
                            ProjectManagerName = x.projectManagerName ?? "",
                            PlanningEngineerName = x.planningEngineerName ?? "",
                            TrialBoardCabinetCode = x.trialBoardCabinetCode ?? "",
                            SingleBoardCabinetType = x.singleBoardCabinetType ?? "",
                            UsingSingleBoardCabinetCount = x.usingSingleBoardCabinetCount ?? "",
                            DosagePCS = x.dosagePCS ?? "",
                            TagNumber = x.tagNumber ?? "",
                            CreatedBy = input.CreatedBy ?? "",
                            CreateDate = Convert.ToDateTime(input.CreateDate),
                            LastUpdatedBy = input.LastUpdatedBy ?? "",
                            LastUpdateDate = Convert.ToDateTime(input.LastUpdateDate),
                        });
                    });

                    count = await ismallBatchTrialService.AddSmallBatchTrialBusinessData(item, list);
                }
                logger.LogInformation($"新增报表数据（小批量试用跟踪电子流）,流程实例号：{_ProcInstId},数量：{count},时间：{DateTime.Now}");
                return Ok(count);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（小批量试用跟踪电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("SmallBatchTrialReportExport")]
        [PageList]
        public async Task<IActionResult> SmallBatchTrialReportExport(SmallBatchTrialReportConditionModel inputCondition)
        {
            inputCondition.pageIndex = 1;
            inputCondition.pageSize = 65535;
            var list = ismallBatchTrialService.GetSmallBatchTrialReportFormData(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\小批量试用跟踪电子流{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }

        /// <summary>
        /// 查询加工-产品-人员配置数据(分页)
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("ProductProcessingPersonnelData")]
        [PageList]
        public async Task<IActionResult> ProductProcessingPersonnelData(ProductProcessingPersonnelConditionModel Input)
        {
            var list = await ismallBatchTrialService.ProductProcessingPersonnelData(Input);
            
            var result = ApiResponsePageList<ProductProcessingPersonnelModel>.CreatePageListByResult(list, Input.pageIndex, Input.pageSize, list.Count);

            return Ok(result);
        }

        /// <summary>
        /// 查询加工-产品-人员配置数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("ProductProcessingPersonnelDataList")]
        public async Task<IActionResult> ProductProcessingPersonnelDataList()
        {
            var list = await ismallBatchTrialService.ProductProcessingPersonnelDataList();
            return Ok(list);
        }

        /// <summary>
        /// 新增加工-产品-人员配置数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("AddProductProcessingPersonnelData")]
        public async Task<IActionResult> AddProductProcessingPersonnelData(ProductProcessingPersonnelModel Input) 
        {
            int count = 0;
            if (Input != null) 
            {
                count = await ismallBatchTrialService.AddProductProcessingPersonnelData(Input);
            }
            return Ok(count);
        }

        /// <summary>
        /// 更新加工-产品-人员配置数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("EditProductProcessingPersonnelData")]
        public async Task<IActionResult> EditProductProcessingPersonnelData(ProductProcessingPersonnelModel Input) 
        {
            int count = 0;
            if (Input != null)
            {
                count = await ismallBatchTrialService.EditProductProcessingPersonnelData(Input);
            }
            return Ok(count);
        }

        /// <summary>
        /// 删除加工-产品-人员配置数据
        /// </summary>
        /// <param name="SysId"></param>
        /// <returns></returns>
        [HttpDelete("DeleteProductProcessingPersonnelData/{SysId:guid}")]
        public async Task<IActionResult> DeleteProductProcessingPersonnelData(Guid SysId)
        {
            int count = await ismallBatchTrialService.DeleteProductProcessingPersonnelData(SysId);
            return Ok(count);
        }

        /// <summary>
        /// 查询产品线信息配置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("ProductLineDetailsData")]
        [PageList]
        public async Task<IActionResult> ProductLineDetailsData(ProductLineDetailsConditionModel Input)
        {
            var list = await ismallBatchTrialService.ProductLineDetailsData(Input);

            var result = ApiResponsePageList<ProductLineDetailsModel>.CreatePageListByResult(list, Input.pageIndex, Input.pageSize, list.Count);

            return Ok(result);
        }


        /// <summary>
        /// 新增产品线信息配置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("AddProductLineDetailsData")]
        public async Task<IActionResult> AddProductLineDetailsData(ProductLineDetailsModel Input)
        {
            int count = 0;
            if (Input != null)
            {
                count = await ismallBatchTrialService.AddProductLineDetailsData(Input);
            }
            return Ok(count);
        }

        /// <summary>
        /// 更新产品线信息配置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("EditProductLineDetailsData")]
        public async Task<IActionResult> EditProductLineDetailsData(ProductLineDetailsModel Input)
        {
            int count = 0;
            if (Input != null)
            {
                count = await ismallBatchTrialService.EditProductLineDetailsData(Input);
            }
            return Ok(count);
        }

        /// <summary>
        /// 删除产品线信息配置
        /// </summary>
        /// <param name="SysId"></param>
        /// <returns></returns>
        [HttpDelete("DeleteProductLineDetailsData/{SysId:guid}")]
        public async Task<IActionResult> DeleteProductLineDetailsData(Guid SysId)
        {
            int count = await ismallBatchTrialService.DeleteProductLineDetailsData(SysId);
            return Ok(count);
        }

        /// <summary>
        /// 查询产品线信息配置-条件检索
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("SearchProductLineDetailsData")]
        [PageList]
        public async Task<IActionResult> SearchProductLineDetailsData(ProductLineDetailsConditionModel Input)
        {
            var list = await ismallBatchTrialService.SearchProductLineDetailsData(Input);

            var result = ApiResponsePageList<ProductLineDetailsModel>.CreatePageListByResult(list, Input.pageIndex, Input.pageSize, list.Count);

            return Ok(result);
        }

        /// <summary>
        /// 返回产品线跟踪工程师
        /// </summary>
        /// <returns></returns>
        [HttpGet("TrialPrackingEngineerDetailsDataList")]
        public async Task<IActionResult> TrialPrackingEngineerDetailsDataList()
        {
            var list = await ismallBatchTrialService.TrialPrackingEngineerDetailsDataList();
            return Ok(list);
        }

        /// <summary>
        /// 返回与父流程相关子流程信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("SelectProcessAssociatedInformationList")]
        public IActionResult SelectProcessAssociatedInformationList(string FatherProcInstId)
        {
            var list = ismallBatchTrialService.SelectProcessAssociatedInformationList(FatherProcInstId);
            return Ok(list);
        }

        /// <summary>
        /// 修改表单试用范围-确定稿
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpdateDetermineTrackMaterialTrackingFromJsonData")]
        public async Task<IActionResult> UpdateDetermineTrackMaterialTrackingFromJsonData(DetermineTrackMaterialTrackingModel DetermineTrackMaterialTracking)
        {
            var list = await ismallBatchTrialService.UpdateDetermineTrackMaterialTrackingFromJsonData(DetermineTrackMaterialTracking);
            return Ok(list);
        }
    }
}
